package com.mxy.myapplication.activity;

import android.app.Activity;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.mxy.myapplication.R;

import java.io.File;

public class MyWebView_Activity extends BaseActivity {

    WebView wv;
    ProgressBar bar;
    String url="https://www.baidu.com";

    private ValueCallback<Uri> mUploadCallback4;//安卓4.1~4.4使用
    private ValueCallback<Uri[]> mUploadCallback5;//安卓5.0+使用


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);

        wv=(WebView) findViewById(R.id.wv);
        bar=(ProgressBar) findViewById(R.id.bar);


        wv.getSettings().setJavaScriptEnabled(true);
        wv.getSettings().setUseWideViewPort(true);
        wv.getSettings().setLoadWithOverviewMode(true);
        wv.getSettings().setSupportZoom(true);
        wv.getSettings().setBuiltInZoomControls(true);
        wv.getSettings().setDisplayZoomControls(false);
        wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);


        wv.setDownloadListener(new WebViewDownLoadListener());
        wv.setWebChromeClient(new WebChromeClient() {//为webview添加进度条
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    bar.setVisibility(View.INVISIBLE);
                } else {
                    if (View.INVISIBLE == bar.getVisibility()) {
                        bar.setVisibility(View.VISIBLE);
                    }
                    bar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            //安卓4.1~4.4调用
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadCallback4 = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");//文件类型
                startActivityForResult(Intent.createChooser(i, "File Chooser"), 999);
            }

            //安卓5.0及以上调用
            @Override
            public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                mUploadCallback5 = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");//文件类型如果想选择所有文件设置 "*/*"
                startActivityForResult(Intent.createChooser(i, "File Chooser"), 999);
                return true;
            }

        });
        wv.setWebViewClient(new WebViewClient(){
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){
                handler.proceed();
            }
        });
        wv.loadUrl(url);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 999&&resultCode== Activity.RESULT_OK) {
            if(Build.VERSION.SDK_INT>=16&&Build.VERSION.SDK_INT<=20){
                if (mUploadCallback4!=null){
                    Bitmap bm = null;
                    //外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
                    ContentResolver resolver = getContentResolver();
                    try {
                        Uri originalUri = intent.getData(); // 获得图片的uri
                        bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);
                        // 这里开始的第二部分，获取图片的路径：
                        String[] proj = { MediaStore.Images.Media.DATA };
                        // 好像是android多媒体数据库的封装接口，具体的看Android文档
                        Cursor cursor = managedQuery(originalUri, proj, null, null, null);
                        // 按我个人理解 这个是获得用户选择的图片的索引值
                        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        // 将光标移至开头 ，这个很重要，不小心很容易引起越界
                        cursor.moveToFirst();
                        // 最后根据索引值获取图片路径
                        String path = cursor.getString(column_index);
                        Uri uri = Uri.fromFile(new File(path));
                        mUploadCallback4.onReceiveValue(uri);
                        mUploadCallback4=null;
                    } catch (Exception e) {
                        mUploadCallback4=null;
                        e.printStackTrace();
                    }
                }
            }else if(Build.VERSION.SDK_INT>=21){
                if (mUploadCallback5 != null) {
                    try{
                        Uri[] uris = null;//文件地址集合
                        //两种情况都要考虑
                        ClipData clipData = intent.getClipData();
                        if (clipData != null) {
                            uris = new Uri[clipData.getItemCount()];
                            for (int i = 0; i < clipData.getItemCount(); i++) {
                                ClipData.Item item = clipData.getItemAt(i);
                                uris[i] = item.getUri();
                            }
                        }
                        //两种情况都要考虑
                        String dataString = intent.getDataString();
                        if (dataString != null){
                            uris = new Uri[]{Uri.parse(dataString)};
                        }
                        mUploadCallback5.onReceiveValue(uris);
                        mUploadCallback5=null;
                    }catch (Exception e){
                        mUploadCallback5=null;
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 给webview添加downloadlistener 调用downloadManager下载apk文件
     */
    class WebViewDownLoadListener implements DownloadListener {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        wv.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        wv.onResume();
    }
}